package realarm.hardwaretest.jniinterface;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class SerialPort {
    /*
     * Do not remove or rename the field mFd: it is used by native method close();
     */
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

    public SerialPort(File device, int baudRate, int flags) throws SerialException {
        /* Check access permission */
        if (!device.canRead() || !device.canWrite()) {
            throw new SerialException("file access permissions denied");
        }
        mFd = serialOpen(device.getAbsolutePath(), baudRate, flags);
        if (mFd == null) {
            throw new SerialException("native open returns null");
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

    // Getters and setters
    protected InputStream getInputStream() {
        return mFileInputStream;
    }

    protected OutputStream getOutputStream() {
        return mFileOutputStream;
    }

    private FileDescriptor serialOpen(String path, int baudrate, int flags){
        return SerialPortControal.SerialOpen(path,baudrate, flags);
    }

    protected void serialClose(){
        SerialPortControal.SerialClose();
    }

}